#include "userbutton.h"
#include "MessageBox.h"
#include "usermenu.h"
#include "passworddialog.h"
#include <QPushButton>
#include <QFontMetrics>
#include <QPainter>
#include <QPixmap>
#include <QMenu>
#include <QPoint>
#include <QSize>
#include <QDebug>
#include <mainwindow.h>
#include "models/curusermodel.h"
#include <models/robotlist.h>

UserButton::UserButton(QWidget *parent) : TouchButton(parent)
{
    connect(CurUserModel::getInstance(), &CurUserModel::usernameChanged, this, [&]() {
        setText(CurUserModel::getInstance()->getUserName());
        QFontMetrics metrics(font());
        int textWidth = metrics.horizontalAdvance(CurUserModel::getInstance()->getUserName());
        setFixedWidth(textWidth + height() * 2); // Add some padding
    });
    connect(this, &QPushButton::clicked, this, &UserButton::onButtonClicked);
}

void UserButton::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    QPixmap leftPixmap(":/images/user.png");
    QPixmap rightPixmap(":/images/combox_drop.png");

    int iconSize = height();
    QRect leftRect(0, 0, iconSize, iconSize);
    QRect rightRect(width() - iconSize, 0, iconSize, iconSize);

    if (isDown()) {
        painter.fillRect(rect(), QColor("#00C8FF"));
    } else {
        painter.fillRect(rect(), Qt::transparent);
    }

    painter.drawPixmap(leftRect, leftPixmap.scaled(iconSize, iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    painter.drawPixmap(rightRect, rightPixmap.scaled(iconSize, iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QRect textRect(iconSize, 0, width() - 2 * iconSize, height());
    painter.drawText(textRect, Qt::AlignCenter, text());
}

void UserButton::onButtonClicked()
{
    QStringList lsBtns;
    lsBtns << tr("修改密码") << tr("重新登录");
    UserMenu *menu = new UserMenu(lsBtns, MainWindow::getInstance());

    // 计算菜单显示位置 - 在按钮正下方
    QPoint btnPos = mapToGlobal(QPoint(0, 0));
    QSize btnSize = size();
    QSize menuSize = menu->sizeHint();

    // 水平居中于按钮，垂直在按钮下方
    int x = btnPos.x() + (btnSize.width() - menuSize.width()) / 2;
    int y = btnPos.y() + btnSize.height();

    menu->move(x, y);

    // 显示菜单并处理结果
    int result = menu->exec();
    delete menu;

    if (result > 0) {
        switch (result) {
        case 1: // 修改密码
        {
            PasswordDialog dlg(MainWindow::getInstance());
            dlg.exec();
        }
        break;
        case 2: // 重新登录
            if(question(this,tr("确定要退出当前用户吗？")) == 0)
            {
                //如果当前连接了机器人，退出
                Robot * pCurRobot = RobotList::getInstance()->getCurRobot();
                if(pCurRobot)
                    pCurRobot->disconnectRobot();
                CurUserModel::getInstance()->logout();
            }
            break;
        }
    }
}
